<?php

namespace Cframe;

class Log{
    private static $msg = array();
    private static $save_path = '';
    private static $save_name = '';

    private function run(){
        static::$save_path = RUNTIME_PATH . "Log" .DS;
        if (!file_exists(static::$save_path) && !mkdir(static::$save_path,0777,true)){
            throw new \Exception("Create Folder Fail");
        }
        if (empty(static::$save_name)) {
            $ds = DS;
            $format = date("Ym/d", time());
            $file = static::$save_path . $format . ".log";
            $dir = dirname($file);
            if (!file_exists($dir)) {
                @mkdir($dir, 0777, true);
            }
            if (!file_exists($dir)) {
                @mkdir($dir, 0777, true);
            }
            static::$save_name = $file;
        }
    }

    public static function save(){
        $file = static::$save_name;
        file_put_contents($file,implode("\n",static::$msg),FILE_APPEND);
        static::$msg = array();
    }

    public static function write($type = 'Log',$msg = ''){
        self::record($type,$msg);
        self::save();
    }


    /**
     *  格式化日志信息
     */
    private function formats($name,$value){
        $time = date("Y-m-d H:i:s",time());
        $run_time = number_format(round(microtime(true)-YF_START_TIME,10),6) . " s";
        $count_file = count(get_included_files());
        $config = array($time,$name,$value,$run_time,$count_file,$_SERVER["PHP_SELF"]);
        static::$msg[] = static::tpl($config);
    }


    /**
     * 记录Log
     * @param string $type Log类型
     * @param string $msg
     */
    private static function record($type = 'Log', $msg = ''){
        if (empty($type)){
            $type = "Log";
        }
        if (is_array($msg)){
            $msg = static::arrayToString($msg);
        }
        static::formats($type,$msg);
    }

    private static function tpl(array $re){
        $str = "[:now][:type] :msg\n[Run_Time][运行时间]: :time\n[Use_Memory][消耗内存]: :memory KB\n[Include_File][引入文件]: :file_count\n[http] :http\n\n";
        $re_r = array(":now",":type",":msg",":time",":file_count",":http",":memory");
        $mem = number_format((memory_get_usage()-YF_STATR_MEM)/1024,2);
        array_push($re,$mem);
        return str_replace($re_r,$re,$str);
    }

    // 帮助函数
    public static function arrayToString($arr) {
        if (is_object($arr)){
            $arr = (array) $arr;
        }
        if (is_array($arr)){
            return var_export($arr,true);
        }
        return $arr ;
    }

    public static function __callStatic($name, $arguments){
        static::run();
        array_unshift($arguments,ucfirst($name));
        call_user_func_array([__CLASS__,"record"],$arguments);
    }
}